package com.danicsoft.daide.command;

import com.danicsoft.daide.token.StandardToken;
import com.danicsoft.daide.token.TokenMap;
import com.danicsoft.daide.token.TokenGroup;

/**
 * Implements the IAM Command. From Eric Wald's <a href="http://pydip.brainshell.org/docs/syntax.html">protocol specification</a>, v0.14:
 * <h4><a name="IAM">client_command = IAM</a> (power) (passcode)</h4>
 * <!--
 * <h4>passcode = number</h4>
 * -->
 * <p>
 * This is sent by the client to the server in place of <b>NME</b>, to indicate
 * that the client is rejoining the game following a loss of connection.
 * <b>Passcode</b> is the passcode which was sent to the client by the server
 * in the original <b>HLO</b> message at the start of the game. The server will
 * reply with <b>YES (IAM (power) (passcode))</b> if the takeover is allowed,
 * or <b>REJ (IAM (power) (passcode))</b> if the passcode is wrong, the game is
 * not waiting for a replacement of the specified power, or the game has not
 * started.
 * </p>
 * <p>
 * Following a successful <b>IAM</b> message, a <b>MAP</b> and <b>HLO</b>
 * message are NOT sent. The player is straight into the game where it left off.
 * Note that there may have been messages which were lost as the connection
 * broke. These messages will <em>not</em> be resent on reconnection.
 * </p>
 * 
 * @author Daniel Yule (daniel.yule@gmail.com)
 * @version 1.0
 */
public class IamCommand extends Command {

	/**
	 * The passcode recieved from the original NME message.
	 */
	public int passcode;

	/**
	 * The power recieved from the original NME message.
	 */
	public StandardToken power;

	/**
	 * Construct a new <code>IamCommand</code> from the
	 * <code>TokenGroup</code> specified.
	 * 
	 * @param tokens
	 *        A <code>TokenGroup</code> that contains the information for an
	 *        <code>IamCommand</code>
	 * @throws ParseException
	 *         If the group did not contain two subgroups, the first with an
	 *         integer, the second with a power.
	 */
	public IamCommand(TokenGroup tokens) throws ParseException {
		super(tokens);
	}

	/**
	 * Construct a new <code>IamCommand</code> for sending to the server.
	 * 
	 * @param passcode
	 *        The passcode previously recieved.
	 * @param power
	 *        A <code>Token</code> corresponding to the power we were playing.
	 */
	public IamCommand(int passcode, StandardToken power) {
		super();
		this.passcode = passcode;
		this.power = power;
	}

	@Override
	public byte getType() {
		return TokenMap.Commands.IAM;
	}

	@Override
	public String toString() {
		return "I am " + power + ", ID :" + passcode;
	}

	public void doIO(TokenIO tokenIO, TokenGroup tokens) throws ParseException {
		power = (StandardToken) tokenIO.doToken(tokenIO.subGroup(tokens), power, TokenMap.powers);
		passcode = tokenIO.doInteger(tokenIO.subGroup(tokens), passcode);

	}

}
